const bcrypt = require('bcryptjs')
const { success,error } = require('../utils/response')
const { getAdminOne } = require("../service/admin.service")
const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.default')

//验证登录
const adminValidator = async(ctx,next) => {
  const { userName,passWord } = ctx.request.body

  if(!userName || !passWord){
    error(ctx,null,'用户名和密码不能为空',400)
    return
  }
  await next()
}
//密码加密
const cryptPassWord = async (ctx,next) => {
  const { passWord } = ctx.request.body
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(passWord, salt); 
  ctx.request.body.passWord = hash
  await next()
}
//验证登录
const verifyLogin = async (ctx,next) => {
  //1、用户是否存在
  const params = ctx.request.body
  try{
   const res = await getAdminOne(params)
   if(!res){
     error(ctx,null,'您还未注册，请先注册',501)
     return
   }
   if(!bcrypt.compareSync(params.passWord,res.passWord)){
     error(ctx,null,'密码输入不正确',501)
     return
   }
  } catch(err){
    console.log(err)
     error(ctx,null,err,502)
     return
  }
  await next()
 }
 //验证token
 const auth = async (ctx,next) => {
  const { authorization = '' } = ctx.request.header
  const token = authorization.replace('Bearer ','')
  try{
    const user = jwt.verify(token,JWT_SECRET)
    ctx.state.user = user
  } catch(err){
    switch(err.name){
      case 'TokenExpiredError':
        return error(ctx,null,'token过期',401)
      case 'JsonWebTokenError':
        return error(ctx,null,'无效token',401)
    }
  }
  await next()
}

module.exports = {
  adminValidator,
  cryptPassWord,
  verifyLogin,
  auth
}